package com.xxgc.demo.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxgc.demo.controller.pojo.SeatPOJO;
import com.xxgc.demo.controller.result.Result;
import com.xxgc.demo.entity.DemoUsers;
import com.xxgc.demo.service.IDemoUsersService;
import com.xxgc.demo.utils.RedisUtil;
import com.xxgc.demo.utils.SpeechSynthesisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
 *
 *   @Author:Sjy
 *   @Date: 2023/9/20-09-20-16:13
 *
 */
@Slf4j
@Tag(name = "整合Redis")
@RestController
@RequestMapping("/redis")
public class Demo3Controller {

    //web层 打通 service层
    @Autowired
    private IDemoUsersService iDemoUsersService;
    @Autowired
    private RedisUtil redisUtil;

    @Operation(summary = "用手机号查用户",description = "手机号")
    @GetMapping("/getUserInfoByPhone")
    public Result<List<DemoUsers>> getUserInfoByPhone(String phone){
        String key = "user_"+phone;
        //缓存是否有这个对象
        boolean b = redisUtil.hasKey(key);
        if(b){//如果有
            log.info("我是缓存中获取的");
            List<DemoUsers> list = (List<DemoUsers>) redisUtil.get(key);
            return Result.ok(list);
        }else{//如果缓存没有
            log.info("我是数据库获取的");
            QueryWrapper<DemoUsers> qw = new QueryWrapper<>();
            qw.eq("phone",phone);
            List<DemoUsers> list = iDemoUsersService.list(qw);
            //往缓存中丢一份 过期时间 30秒之后过期
            redisUtil.set(key,list,60 * 60 * 12);
            return Result.ok(list);
        }
    }

    @Operation(summary = "通过手机号修改用户名",description = "修改用户名")
    @PutMapping("/updateUserNameByPhone")
    public Result updateUserNameByPhone(String phone,String name){
        UpdateWrapper<DemoUsers> uw = new UpdateWrapper<>();
        uw.eq("phone",phone);
        uw.set("name",name);
        //在数据库改了
        iDemoUsersService.update(uw);
        String key = "user_"+phone;
        boolean b = redisUtil.hasKey(key);
        if(b) {//如果有
            redisUtil.del(key);
        }
        return Result.ok();
    }

    //写两个接口
    //接口1  获取手机号 在控制台显示验证码 1分钟失效
    @Operation(summary = "获取邮箱的验证码",description = "返回验证码")
    @PostMapping("/getEmailLoginCode")
    public Result getEmailLoginCode(String email){
        //丢到缓存中
        String key = "email_"+email;
        if(redisUtil.hasKey(key)){
            return Result.error().msg("请一分钟之后重发");
        }
        //生成一个验证码
        String code = RandomUtil.randomNumbers(6);
        //给用户的邮箱发送验证码
        MailUtil.send(email, "签卡系统用户注册", "请不要将验证码告诉其他人。验证码："+code+"。验证码1分钟后失效", false);
        //同步到redis里面
        redisUtil.set(key,code,60);
        return Result.ok();
    }

    //接口2  验证码带手机号的注册校验
    @Operation(summary = "验证码和邮箱注册",description = "注册")
    @PostMapping("/insertUserByEmailAndCode")
    public Result insertUserByEmailAndCode(String email,String code){
        String key = "email_"+email;
        if(!redisUtil.hasKey(key)){
            return Result.error().msg("请重新获取验证码");
        }
        String codeRedis = (String) redisUtil.get(key);
        if(codeRedis.equals(code)){
            redisUtil.del(key);
            //走注册逻辑 验证邮箱是否已经注册
            return Result.ok().msg("注册成功");
        }
        return Result.ok().msg("验证码错误");
    }

    //周末作业
    //写一个美团叫号功能，有取号，过号（顺延3桌，过号超10桌失效），叫号的功能用 redis 注解！！！实现
    @Operation(summary = "订座取号",description = "取号功能")
    @GetMapping("/getBookingCall")
    public Result getBookingCall(Integer seatType){
        redisUtil.incr("number",1);
        //桌号获取出来
        Integer number = (Integer) redisUtil.get("number");
        String zuo = "";
        if(number < 100){
            zuo = "0" + number;
        }
        //拼接 补0
        if(number < 10){
            zuo = "0" + number;
        }
        switch (seatType){
            case 1:
                zuo = "小桌：" + zuo;
                break;
            case 2:
                zuo = "中桌：" + zuo;
                break;
            case 3:
                zuo = "大桌：" + zuo;
                break;
            case 4:
                zuo = "圆桌：" + zuo;
                break;
            case 5:
                zuo = "包间：" + zuo;
                break;
        }
        //对象的封装
        SeatPOJO seatPOJO = new SeatPOJO(zuo, number, false, null, seatType,0);
        List<SeatPOJO> list = null;
        if(redisUtil.hasKey("seat_list")){
            list = (List<SeatPOJO>) redisUtil.get("seat_list");
        }else{
            list = new ArrayList<>();
        }
        list.add(seatPOJO);
        redisUtil.set("seat_list",list);
        return Result.ok(zuo);
    }


    @Operation(summary = "叫号功能",description = "叫号")
    @GetMapping("/callNumber")
    public Result callNumber(Integer seatType){
        List<SeatPOJO> list = (List<SeatPOJO>) redisUtil.get("seat_list");
        for (SeatPOJO seatPOJO : list) {
            //如果被叫过了
            if(seatPOJO.isCall()){
                continue;
            }
            //判断桌的类型是否相等
            if(seatPOJO.getSeatType() == seatType){
                if(seatPOJO.getWaiting() == 0){
                    //修改已经被叫过的内容
                    seatPOJO.setCallTime(new Date());
                    seatPOJO.setCall(true);
                    redisUtil.set("seat_list",list);

                    String seatName = seatPOJO.getSeatName();
                    String message = seatName +"顾客，请您用餐啦。";
                    //真实的读出来
                    SpeechSynthesisUtil speechSynthesisUtil = new SpeechSynthesisUtil();
                    speechSynthesisUtil.speak(message+message+message);

                    return Result.ok(seatName);
                }else{
                    seatPOJO.setWaiting(seatPOJO.getWaiting() - 1);
                }
            }
        }
        return Result.error().msg("没有排队，可直接用餐");
    }

    @Operation(summary = "过号功能",description = "过号")
    @GetMapping("/overNumbered")
    public Result overNumbered(Integer seatType,Integer number){
        List<SeatPOJO> list = (List<SeatPOJO>) redisUtil.get("seat_list");
        for (SeatPOJO seatPOJO : list) {
            if(seatPOJO.getSeatType() == seatType){
                if(seatPOJO.getSeatNum() == number){
                    seatPOJO.setCall(false);
                    seatPOJO.setWaiting(3);
                }
            }
        }
        redisUtil.set("seat_list",list);
        return Result.ok();
    }


}
